package com.github.binarylei.security.bolt;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Map;

/**
 * @author: leigang
 * @version: 2018-04-07
 */
public class WorldSplitBolt implements IRichBolt {

    private static final long serialVersionUID = 1L;
    private OutputCollector collector;

    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector collector) {
        this.collector = collector;
    }

    private boolean flag = true;

    @Override
    public void execute(Tuple tuple) {
        try {
            // 获取上一个组件声明的Field
            String sentences = tuple.getStringByField("sentences");

            /*if (flag && sentences.contains("1")) {
                flag = false;
                throw new RuntimeException("WorldSplitBolt 异常");
            }*/

            String[] words = sentences.split(" ");
            for (String word : words) {
                this.collector.emit(tuple, new Values(word));
            }
            collector.ack(tuple);
        } catch (Exception e) {
            e.printStackTrace();

            collector.fail(tuple);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("word"));
    }

    @Override
    public Map<String, Object> getComponentConfiguration() {
        return null;
    }

    @Override
    public void cleanup() {

    }
}
